<?php
function dt_setup_ajax(){
	// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
	global $post;
	wp_localize_script(
		'dt_ajaxing',
		'dt_ajax',
		array(
			'ajaxurl'	=> admin_url( 'admin-ajax.php' ),
			'post_id'   => $post?$post->ID:''
		)
	);
}
add_action('wp_enqueue_scripts', 'dt_setup_ajax');

// portfolio part
function dt_ajax_portfolio() {
	$dt_slug = isset( $_POST['dt_slug'] )?$_POST['dt_slug']:'';
	$dt_page = isset( $_POST['dt_page'] )?$_POST['dt_page']:null;
	$dt_post_id = isset( $_POST['dt_post_id'] )?intval( $_POST['dt_post_id'] ):null;
    $dt_ajaxurl = isset( $_POST['dt_ajaxurl'] )?strip_tags($_POST['dt_ajaxurl']):'';
    $dt_layout = isset( $_POST['dt_layout'] )?strip_tags($_POST['dt_layout']):'';
	
	$args = array(
		'filter'	=> $dt_slug,
		'paged'		=> $dt_page,
		'post_id'	=> $dt_post_id,
        'ajaxurl'   => $dt_ajaxurl
	);
	
    $result = array(
        'html'      => '',
        'paginator' => ''
    );
    
    if( post_password_required($dt_post_id) ) {
        $result['html'] = 'This is password protected post';
	}elseif( 'portfolio' == $dt_layout ) {
        $result = dt_portfolio_page( $args );
    }elseif( 'gallery' == $dt_layout ) {
        $result = dt_gallery_page( $args );
    }elseif( 'photos' == $dt_layout ) {
        $result = dt_photo_page( $args );
    }
    
	// generate the response
    $response = json_encode(
		array(
			'success'		=> true ,
            'ajaxurl'       => $dt_ajaxurl,
			'category'		=> $dt_slug,
			'html_content'	=> $result['html'],
            'post_id'       => $dt_post_id,
			'paginator'		=> $result['paginator']
		)
	);

	// response output
    header( "Content-Type: application/json" );
    echo $response;

    // IMPORTANT: don't forget to "exit"
    exit;
}

add_action( 'wp_ajax_nopriv_dt_ajax_portfolio', 'dt_ajax_portfolio' );
add_action( 'wp_ajax_dt_ajax_portfolio', 'dt_ajax_portfolio' );

// display portfolio
if( !function_exists('dt_portfolio_page') ) {
    function dt_portfolio_page( $ajx_args ) {
        global $wp_query, $paged;
        $paginator = '';
        
        if( !$paged = $ajx_args['paged'] ) {
            $paged = 1;
        }
        
        $defaults = array(
            'list'          => array(),
            'ppp'           => '',
            'orderby'       => 'date',
            'order'         => 'DESC',
            'slug'          => 'portf_cat'//delete in future
        );
        $options = get_post_meta( $ajx_args['post_id'], 'dt_portfolio_layout', true );
        $options = wp_parse_args( $options, $defaults );

        $portf_slug = $options['slug'];
                                
        $args = array(
            'post_type'	    => 'dt_portfolio',
            'paged'		    => $paged,
            'orderby'       => $options['orderby'],
            'order'         => $options['order'],
            'post_status'   => 'publish'
        );
                                        
        if( !empty($options['ppp']) ){
            $args['posts_per_page'] = $options['ppp'];
            unset($options['ppp']);
        }
                        
        if( 'all' != $ajx_args['filter'] ) {
            if( 'none' != $ajx_args['filter'] ) {
                $args['tax_query'] = array(	
                    array(
                        'taxonomy'	=> 'dt_portfolio_category',
                        'field'		=> 'slug',
                        'terms'		=> strip_tags( (string) $ajx_args['filter'] )
                    )
                );
            }else {
                $tax = get_terms( 'dt_portfolio_category', array('fields' =>'ids') );
                $args['tax_query'] = array(	
                    array(
                        'taxonomy'	=> 'dt_portfolio_category',
                        'field'		=> 'id',
                        'terms'		=> $tax,
                        'operator'	=> 'NOT IN'
                    )
                );
            }
        }elseif( $options['list'] ) {
            $args['tax_query'] = array(	
                array(
                    'taxonomy'	=> 'dt_portfolio_category',
                    'field'		=> 'id',
                    'terms'		=> current( $options['list'] ),
                    'operator' 	=> ( 'only' == key($options['list']) )?'IN':'NOT IN',
                )
            );
        }

        $wp_query = new Wp_Query( $args );
        // html content
        ob_start();
        
        if( $wp_query->have_posts() ) {
            while( $wp_query->have_posts() ) {
                $wp_query->the_post();
                get_template_part( 'dt_portfolio', 'content' );            
            };
        }else {
        ?>
            <p><?php _e( 'Sorry, but page is empty.', LANGUAGE_ZONE ); ?></p>
        <?php
        };
        
        $html = ob_get_clean();
        
        //pagination
        
        ob_start();
        
        if( function_exists('wp_pagenavi') ) {
            dt_get_where_filter_params(
                array(
                    'slug'      => $ajx_args['filter'],
                    'ajaxurl'   => $ajx_args['ajaxurl'],
                    'pageurl'   => get_permalink($ajx_args['post_id'])
                )
            );
            wp_pagenavi( '', '', 'pages', true, true );
        }
        
        $paginator = ob_get_clean();
        
        return $result = array(
            'html'      => $html,
            'paginator' => $paginator 
        );
    }
}

// display gallery
if( !function_exists('dt_gallery_page') ) {
    function dt_gallery_page( $ajx_args ) {
        global $wp_query, $paged;
        $defaults = array(
            'list'      => array(),
            'ppp'       => '',
            'orderby'   => 'date',
            'order'     => 'DESC'
        );
        $opts = get_post_meta( $ajx_args['post_id'], 'dt_gallery_layout', true );
        $opts = wp_parse_args( $opts, $defaults );
        
        if( !$paged = $ajx_args['paged'] ) {
            $paged = 1;
        }
                                
        $args = array(
            'post_type'	=> 'dt_gallery',
            'paged'		=> $paged,
            'orderby'   => $opts['orderby'],
            'order'     => $opts['order']
        );
                                        
        if( !empty($opts['ppp']) ){
            $args['posts_per_page'] = $opts['ppp'];
            unset($opts['ppp']);
        }
                        
        if( 'all' != $ajx_args['filter'] ) {
            if( 'none' != $ajx_args['filter'] ) {
                $args['tax_query'] = array(	
                    array(
                        'taxonomy'	=> 'dt_gallery_category',
                        'field'		=> 'slug',
                        'terms'		=> strip_tags( (string) $ajx_args['filter'] )
                    )
                );
            }else {
                $tax = get_terms( 'dt_gallery_category', array('fields' =>'ids') );
                $args['tax_query'] = array(	
                    array(
                        'taxonomy'	=> 'dt_gallery_category',
                        'field'		=> 'id',
                        'terms'		=> $tax,
                        'operator'	=> 'NOT IN'
                    )
                );
            }
        }elseif( $opts['list'] ) {
            $args['tax_query'] = array(	
                array(
                    'taxonomy'	=> 'dt_gallery_category',
                    'field'		=> 'id',
                    'terms'		=> current( $opts['list'] ),
                    'operator' 	=> ( 'only' == key($opts['list']) )?'IN':'NOT IN',
                )
            );
        }

        $wp_query = new Wp_Query( $args );
        
        add_filter( 'the_excerpt', 'dt_password_excerpt' );
        add_filter( 'the_password_form', 'dt_gallery_passform' );
        // html content
        ob_start();
        if( $wp_query->have_posts() ) {
            while( $wp_query->have_posts() ) {
                $wp_query->the_post();
                get_template_part('dt_gallery', 'content');            
            };
        }else {
        ?>
            <p><?php _e( 'Sorry, but page is empty.', LANGUAGE_ZONE ); ?></p>
        <?php
        };
        
        $html = ob_get_clean();
        
        remove_filter( 'the_excerpt', 'dt_password_excerpt' );
        remove_filter( 'the_password_form', 'dt_gallery_passform' );
        //pagination
        
        ob_start();
                
        if( function_exists('wp_pagenavi') ) {
            dt_get_where_filter_params(
                array(
                    'slug'      => $ajx_args['filter'],
                    'ajaxurl'   => $ajx_args['ajaxurl'],
                    'pageurl'   => get_permalink($ajx_args['post_id'])
                )
            );
            wp_pagenavi( '', '', 'pages', true, true );
        }
        
        $paginator = ob_get_clean();
        
        return $result = array(
            'html'      => $html,
            'paginator' => $paginator 
        );
    }
}

// display photos
if( !function_exists('dt_photo_page') ) {
    function dt_photo_page( $ajx_args ) {
        global $wp_query, $paged, $wpdb;
        
        if( !$paged = $ajx_args['paged'] ) {
            $paged = 1;
        }

        $defaults = array(
            'orderby'   => 'menu_order',
            'order'     => 'ASC'
        );
        $opts = get_post_meta( $ajx_args['post_id'], 'dt_gallery_layout', true );
        $opts = wp_parse_args( $opts, $defaults );

        // select ID of the albums in selected taxonomy
        $in_select = '';
        if( !empty($opts['list']) && is_array($opts['list']) ) {
            $in_select .= sprintf( ' AND %s.term_id', $wpdb->term_taxonomy );
            $key = key( $opts['list'] );
            if( 'except' == $key ) {
                $in_select .= ' NOT';
            }
            $in_select .= sprintf( ' IN(%s)', implode( ',', current($opts['list']) ) );
        }

        $query_str = sprintf(
            'SELECT %3$s.ID FROM %1$s 
            JOIN %2$s ON %1$s.term_taxonomy_id = %2$s.term_taxonomy_id 
            JOIN %3$s ON %2$s.object_id = %3$s.ID
            WHERE %1$s.taxonomy = "%4$s" AND %3$s.post_status = "publish"%5$s
            GROUP BY %3$s.ID',
            $wpdb->term_taxonomy,
            $wpdb->term_relationships,
            $wpdb->posts,
            'dt_gallery_category',
            $in_select
        );

        dt_get_where_filter_params( $query_str );
                                
        $args = array(
            'post_type' 		=> 'attachment', 
            'post_mime_type'	=> 'image',
            'post_status' 		=> 'inherit',
            'paged'		        => $paged,
            'orderby'           => $opts['orderby'],
            'order'             => $opts['order']
        );
                                        
        if( !empty($opts['ppp']) ){
            $args['posts_per_page'] = $opts['ppp'];
            unset($opts['ppp']);
        }

        // mpdify query
        add_filter( 'posts_where' , 'dt_posts_parents_where' );
        $wp_query = new Wp_Query( $args );
        remove_filter( 'posts_where' , 'dt_posts_parents_where' );
        remove_filter( 'the_content', 'prepend_attachment' );
        
        // html content
        ob_start();
        
        if( $wp_query->have_posts() ) {
            while( $wp_query->have_posts() ) {
                $wp_query->the_post();
                get_template_part('dt_photos', 'content');            
            };
        }else {
        ?>
            <p><?php _e( 'Sorry, but page is empty.', LANGUAGE_ZONE ); ?></p>
        <?php
        };
        
        $html = ob_get_clean();
        
        //pagination
        
        ob_start();
                
        if( function_exists('wp_pagenavi') ) {
            dt_get_where_filter_params(
                array(
                    'slug'      => $ajx_args['filter'],
                    'ajaxurl'   => $ajx_args['ajaxurl'],
                    'pageurl'   => get_permalink($ajx_args['post_id'])
                )
            );
            wp_pagenavi( '', '', 'pages', true, true );
        }
        
        $paginator = ob_get_clean();
        
        return $result = array(
            'html'      => $html,
            'paginator' => $paginator 
        );
    }
}